import { ref, reactive, computed } from 'vue'
import { defineStore } from 'pinia'

export const useStore = defineStore(
  'movie',
  () => {
    const geolocation = reactive({ latitude: 0, longitude: 0 }) //当前位置

    const bottomTabBarActiveIndex = ref(0)

    const currentCity = reactive({ id: 0, nm: '' }) //当前城市
    const historyCities = ref([]) //最近3个城市
    const hotCities = ref([]) //热门城市
    const allCities = ref([]) //所有城市
    const movieList = ref([]) //电影列表
    const movieIds = ref([]) //电影id列表
    const total = ref(0) //电影总数
    const topRankMovies = ref([]) // 好评榜电影
    const topRankTitle = ref('')

    const cinemas = ref([]) //电影院列表

    const activeTab = ref(1)


    const topExpectedMovies = ref([]) // 最期待上映电影
    const hasMoreExpectedMovies = ref(false)

    const coming = ref([]) //即将上映电影
    const comingIds = ref([]) //即将上映电影id

    const searchHistory = ref([]); //搜索历史

    const movieDetailPage = reactive({
      backgroundColor: '',
      movieInfo: {},
      movieScore: {},
      movieBrief: '',
      movieActors: [],
      movieClipList: [],
      movieGallery: [],
      movieShortComments: {},
      movieQuestions: {},
      movieReviews: {},
      movieMaterilas: [],
      movieBoxOffice: {},
      movieRelatedNews: [],
      movieRelatedMovies: [],
      onSale: false,
      guideToWish: true,
    })



    const feed = ref({})




    const formattedCredits = computed(() => {
      return movieDetailPage.movieActors.reduce((acc, item) => {
        const role = acc.find(roleItem => roleItem.cr === item.cr);
        if (role) {
          role.items.push(item);
        } else {
          let roleName = item.desc.split(':')[0].trim();
          if (item.cr === 1) {
            roleName = "演员";
          }
          acc.push({
            roleName: roleName,
            cr: item.cr,
            items: [item]
          });
        }
        return acc;
      }, []);
    });




    function setActiveTab (index) {
      activeTab.value = index
    }



    function setGeolocation (lat, lng) {
      geolocation.latitude = lat
      geolocation.longitude = lng
    }


    function setBottomTabBarActiveIndex (index) {
      bottomTabBarActiveIndex.value = index
    }

    function setCurrentCity (city) {
      currentCity.id = city.id
      currentCity.nm = city.nm
    }

    //设置最近访问城市列表
    function setHistoryCities (city) {
      // 检查 city 是否已经存在于 historyCities 中
      const cityExists = historyCities.value.some((c) => c.id === city.id)
      if (!cityExists) {
        // 如果 hotCities 的长度超过3，则删除第一个元素
        if (historyCities.value.length >= 3) {
          historyCities.value.shift()
        }
        historyCities.value.push(city)
      }
    }
    function setHotCities (cityList) {
      //设置热门城市
      hotCities.value = cityList
    }

    function setAllCities (cities) {
      allCities.value = cities
    }

    function setMovieList (list) {
      movieList.value = list
    }

    function setMovieIds (ids) {
      movieIds.value = ids
    }

    function setTotal (num) {
      total.value = num
    }

    function setTopRankMovies (list) {
      topRankMovies.value = list
    }
    function setTopRankTitle (title) {
      topRankTitle.value = title
    }

    function setCinemas (cinemaList) {
      cinemas.value = cinemaList
    }

    function setTopExpectedMovies (list) {
      topExpectedMovies.value = list
    }

    function setHasMoreExpectedMovies (bool) {
      hasMoreExpectedMovies.value = bool
    }

    function setComingMovieList (list) {
      coming.value = list
    }

    function setComingMovieIds (ids) {
      comingIds.value = ids
    }

    //设置最近访问城市列表
    function setSearchHistory (keyword) {
      // 检查 city 是否已经存在于 searchHistory 中
      const keywordExists = searchHistory.value.some((kw) => kw === keyword)
      if (!keywordExists) {
        // 如果长度超过3，则删除最后一个元素
        if (searchHistory.value.length >= 3) {
          searchHistory.value.pop()
        }
        searchHistory.value.unshift(keyword)
      }
    }

    //删除指定的搜索关键词
    function deleteSearchHistory (keyword) {
      searchHistory.value = searchHistory.value.filter(item => item !== keyword)
    }

    function setMovieDetailPage (moviePage) {
      movieDetailPage.backgroundColor = moviePage.backgroundColor
      movieDetailPage.movieInfo = moviePage.movieInfo
      movieDetailPage.movieScore = moviePage.movieScore
      movieDetailPage.movieBrief = moviePage.movieBrief
      movieDetailPage.movieActors = moviePage.movieActors
      movieDetailPage.movieClipList = moviePage.movieClipList
      movieDetailPage.movieGallery = moviePage.movieGallery
      movieDetailPage.movieShortComments = moviePage.movieShortComments
      movieDetailPage.movieQuestions = moviePage.movieQuestions
      movieDetailPage.movieReviews = moviePage.movieReviews
      movieDetailPage.movieMaterilas = moviePage.movieMaterilas
      movieDetailPage.movieBoxOffice = moviePage.movieBoxOffice
      movieDetailPage.movieRelatedNews = moviePage.movieRelatedNews
      movieDetailPage.movieRelatedMovies = moviePage.movieRelatedMovies
      movieDetailPage.onSale = moviePage.onSale
      movieDetailPage.guideToWish = moviePage.guideToWish
    }


    function setFeed (data) {
      feed.value = data
    }




    return {
      geolocation,
      bottomTabBarActiveIndex,
      currentCity,
      historyCities,
      hotCities,
      allCities,
      movieList,
      movieIds,
      total,
      topRankMovies,
      topRankTitle,
      cinemas,
      topExpectedMovies,
      hasMoreExpectedMovies,
      coming,
      comingIds,
      searchHistory,
      movieDetailPage,
      activeTab,
      feed,
      formattedCredits,
      setGeolocation,
      setBottomTabBarActiveIndex,
      setCurrentCity,
      setHistoryCities,
      setHotCities,
      setAllCities,
      setMovieList,
      setMovieIds,
      setTotal,
      setTopRankMovies,
      setTopRankTitle,
      setCinemas,
      setTopExpectedMovies,
      setHasMoreExpectedMovies,
      setComingMovieList,
      setComingMovieIds,
      setSearchHistory,
      deleteSearchHistory,
      setMovieDetailPage,
      setActiveTab,
      setFeed,

    }
  },
  {
    persist: true,
  },
)
